<?php
namespace Home\Controller;
use Common\Controller\CommonController;
use Org\Util\Wechat;

class CustomerController extends CommonController {
	
	private $wx = null;
	
	public function _initialize(){
		set_time_limit(0);
		$this->wx = new Wechat(C('test'));
		parent::_initialize();
	}
	
	function index(){
		//小区列表
		
		$this->display('index');
	}
	
	//用户管理列表
	public function customer_list(){
		//所有项目
		$list_apt=M('apt')->select();
		//P($list_apt);
		$this->assign('list_apt',$list_apt);
		
		$customer=M('customer');
		//用户姓名或手机号
		$keyword=trim(I('keyword'));
		//用户的小区
		$type=I('type');
		//客户类型
		$type_customer=I('type_customer'); 
		$whereStr = ' `openid` != "" ';
		if(!empty($keyword)){
			$whereStr .= ' and `name` like "%'. $keyword .'%" or `phone` like "%'.$keyword.'%" ';
			$whereArr['keyword'] = $keyword;
		}
		if(!empty($type)){
			$whereStr .= ' and `plot` = "'.$type.'"';
			$whereArr['type'] = $type;
		}
		if(!empty($type_customer)){
			$whereStr .= ' and `status_customer` = "'.$type_customer.'"';
			$whereArr['status_customer'] = $type_customer;
		}
		
	    //$where['name'] = array('like','%'.$keyword.'%');
		$count      = $customer->where($whereStr)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
        $list = $customer->limit($Page->firstRow.','.$Page->listRows)->where($whereStr)->order('ctime desc')->select();
        
        foreach ($list as $key => $value) {
			$plot=M('apt')->where('id="'.$value['plot'].'"')->find();
			$name=$plot['name'];
			$list[$key]['names']=$name;
		}
        $arr=array('page'=>$show,'list'=>$list,'count'=>$count);
        //print_r($list);exit;
        $this->assign('whereArr',$whereArr); 
		$this->assign('list',$arr);
		$this->display('index');
	}
	
	
	
	
	
	//升级为优质用户
	public function shengji(){
		$id=I('id');
		$status_customer=I('status_customer');
		$data=array(
			'status_customer'=>$status_customer,
		);
		$res=M('customer')->where('id="'.$id.'"')->save($data);
		if(!false==$res){
			$this->redirect('Customer/customer_list');
		}
		
		
	} 
		
	//导出csv格式的表格---用户的
	
	public function exportcsv_customer() {//exit('11100');
		$customers=M('customer');
		//用户姓名或手机号
		$keyword=trim(I('keyword'));
		//用户的小区
		$type=I('type');
		//客户类型
		$type_customer=I('type_customer'); 
		$whereStr = ' `openid` != "" ';
		if(!empty($keyword)){
			$whereStr .= ' and `name` like "%'. $keyword .'%" or `phone` like "%'.$keyword.'%" ';
			$whereArr['keyword'] = $keyword;
		}
		if(!empty($type)){
			$whereStr .= ' and `plot` = "'.$type.'"';
			$whereArr['type'] = $type;
		}
		if(!empty($type_customer)){
			$whereStr .= ' and `status_customer` = "'.$type_customer.'"';
			$whereArr['status_customer'] = $type_customer;
		}
		
		//P($list);
		$str = "客户姓名,客户联系方式,性别,项目,房号,邮箱,生日,客户类型\r\n";
		
		$user = session('LG_USER');
		$name=$user['username'];
		
		$list = $customers->where($whereStr)->order('ctime desc')->select();
		
		
		foreach($list as $key=>$value){
			
			$plot = $value['plot'];
			$customer=M('apt')->where('id="'.$plot.'"')->find();
		
			$list[$key]['p_name']=$customer['name'];
			
		}
		//P($list);
		foreach($list as $k => $value){
			$name=$value['name'];
			$phone=$value['phone'];
			$sex=$value['sex'];
			if($sex==1){
				$sex='男';
			}else{
				
				$sex='女';
			}
			$plot=$value['p_name'];
			$num=$value['num'];
			$email=$value['email'];
			$birth=$value['birth'];
			$status_customer=$value['status_customer'];
			if($status_customer==1){
				$status_customer='普通用户';
			}else{
				
				$status_customer='优质用户';
			}
			
			$str .= "".$name.",".$phone.",".$sex.",".$plot.",".$num.",".$email.",".$birth.",".$status_customer."\r\n";
			
		} 
		//P($str);
		$filename = date('Ymd').'.csv'; //设置文件名
		if(filesize($file)>1024){
			$file = getcwd().'/aaa.csv';
			//dump($file);exit;
			file_put_contents($file,$str);
			//dump($str);exit;
			if (file_exists($file)) {
					$filesize=filesize($file)+1000;
					
					header('Content-Description:File Transfer');
					header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
					header('Content-Transfer-Encoding:binary');
					header("Accept-Ranges: bytes");
					header('Expires:0');
					header('Cache-Control:must-revalidate');
					header('Pragma:public');
					header("Content-Length:".$filesize);
					header('Content-Disposition: attachment; filename='.$filename);
						//打开文件
						$fp = fopen($file, "rb");
						//dump($fp);exit;
						//设置指针位置
						fseek($fp,0);
						while (!feof($fp)) {
							//虚幻输出
							//设置文件最长执行时间
							set_time_limit(0);
							print (fread($fp, 1024 * 150)); //输出文件
							flush(); //输出缓冲
							ob_flush();
						}
						fclose($fp);
					
					unlink($file);
					exit ();
				}else{
					echo "err";die();
				}
			}else{
				header("Content-type:text/csv");
				header("Content-Disposition:attachment;filename=".$filename);
				//header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
				header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
				header('Expires:0');
				header('Pragma:public');
				$str = iconv('utf-8', 'gb2312', $str);
				echo $str;
			}
		} 	
	
	
	
	
	
	//管理员管理
	public function kefu_list(){
		
		$sy_rbac_manager=M('rbac_manager');
		$count      = $sy_rbac_manager->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		$list=$sy_rbac_manager->limit($Page->firstRow.','.$Page->listRows)->select();
		$arr=array('page'=>$show,'list'=>$list,'count'=>$count);
		$this->assign('list',$arr);
		
		$this->display('kefu');
	}

	/*修改客服的服务中心首页*/
	public function sc_up(){
		$id=I('id');
		//查找客服
		$list=M('rbac_manager')->where('id="'.$id.'"')->find();
		$sc=$list['sc'];
		//查找客服锁在的服务中心
		$list_s=M('sc')->where('id="'.$sc.'"')->find();
		//查找所有的服务中心
		$list_sc=M('sc')->select();
		//print_r($list_s);exit('@@@');
		$this->assign('id',$id);
		$this->assign('list_s',$list_s);
		$this->assign('list_sc',$list_sc);
		$this->display('update_question');
	}
	/*修改客服的服务中心首页*/
	public function del_usre(){
		$id=I('id');
		$where['id']=$id;
		$list=M('rbac_manager')->where($where)->find();
		$kf=M('kf')->where('openid="'.$list['openid'].'"')->find();
		if($kf){
			P('请先清除客服绑定，再重试');
		}else{
			$re=M('rbac_manager')->where($where)->delete();
			if($re){
				$this->redirect('Customer/kefu_list');
			}else{
				P('删除失败，请重试');
			}
		}
		
		
	}
	/*修改客服的服务中心首页*/
	public function del_kf(){
		$id=I('id'); 
	
		$where['id']=$id;
		$list=M('rbac_manager')->where($where)->find();
		
		$kfo=M('kf')->where('openid="'.$list['openid'].'"')->find();
		
		$kf=M('kf')->where('openid="'.$list['openid'].'"')->delete();
	
		
		

		$kflsit=$this->wx->getCustomServiceKFlist();
		$kfLis = array();
		foreach($kflsit['kf_list']  as $val){
			$kfLis[] = $val['kf_account']; 
		}
		if(in_array($kfo['kf_account'], $kfLis)){
				$rs = $this->wx->deleteKFAccount($kfo['kf_account']);
				if($rs){
					$this->ajaxReturn(array('s'=>true,'info'=>"清除成功"));
				}
		}else{
				$this->ajaxReturn(array('s'=>true,'info'=>"已清除！"));
		}

		
	}

	//修改管理员的服务中心
	public function update_sc(){
		$id=I('id');
		$sc_id=I('sc_id');
		$where=array('id'=>$id,);
		$res_save=M('rbac_manager')->where($where)->data(array('sc'=>$sc_id))->save();
		if (false==$res_save) {
			P('修改失败，请重试');
		}else{
			$this->redirect('Customer/kefu_list');
		}
	}



//修改管理员的密码
	public function uppwd(){
		$user = session('LG_USER');
		//P($user);
		$newpwd=md5(I('newpwd'));
		$where['id']=$user['id'];
		$res_save=M('rbac_manager')->where($where)->data(array('password'=>$newpwd))->save();
		if ($res_save) {
			$this->ajaxReturn(array('s'=>true,'info'=>"修改成功，请重新登入"));
		}else{
			$this->ajaxReturn(array('s'=>false,'info'=>"修改失败,无权限"));
		}
	}




	
	//注册完善客服信息 
	public function registerkefu(){
		$user = session('LG_USER');
		if(empty($user['openid'])){
			P('你还没有绑定微信，暂时不能配置客服信息。');
		}
		$kf = M('Kf')->where('openid="'.$user['openid'].'"')->find();
		if(!empty($kf)){
			$this->assign('kf',$kf);
		}else{
			
		}
		$kfconf = C('kf');
		$kfconf['key'] = $kfconf['prefix'].'****';
		$this->assign('kfConf',$kfconf);
		$this->display();
	}
	
	//新建客服
	public function kf_register(){
		$d = I('post.');
		if(empty($d['kf_nickame'])||empty($d['kf_wx'])||empty($d['password'])){
			
		}
		$user = session('LG_USER');
		$where = array('openid' =>	$user['openid']);
		$dat = array(
			'openid' =>	$user['openid'],
			'kf_account'	=>	$this->initNewKFAccount(),
			'kf_nickname'	=>	$d['nickname'], 
			'kf_wx'	=>	$d['kf_wx'],
			'password'	=>	123456,
			'introduce' =>$d['introduce'],
		);
		$kf = M('Kf')->where($where)->find();
		$errCount = 0;
		$errMes = '';
		if(!empty($kf)){
			$rs = M('Kf')->where($where)->save($dat);
			$rs = $this->wx->addKFAccount($dat['kf_account'],$dat['kf_nickname'],$dat['password']);
		}else{
			$rs = M('Kf')->data($dat)->add();
			//新增客服
			$rs = $this->wx->addKFAccount($dat['kf_account'],$dat['kf_nickname'],$dat['password']);
			if(!$rs){
				$errCount++;
				$errMes .= '新增客服，更新服务失败';
			}
			//发启邀请
			$rs = $this->wx->inviteworkerAccount($dat['kf_account'],$dat['kf_wx']);
			if(!$rs){
				$errCount++;
				$errMes .= '新增客服，发启邀请失败';;
			} 
		}
		if($errCount>0){
			$this->ajaxReturn(array('s'=>false,'m'=>$errMes));
		}else{
			$this->ajaxReturn(array('s'=>true,'m'=>'操作完成'));
		}
	}
	
	public function initNewKFAccount(){
		$ct = M('Kf')->max('id');
		if(empty($ct)){
			$ct=0;
		}
		$ct = '0000'.($ct+1);
		$ct = substr($ct,-4,4);
		$kfConf = C('kf');
		return $kfConf['prefix'].$ct.'@'.$kfConf['suffix'];
	}
	
	public function kf_setHeadimg(){  
		$str = I('post.imgData'); 
		$kf_account = I('post.kf_account'); 
		if(empty($str)){ 
			$this->ajaxReturn(array('s'=>false,'m'=>'图片上传失败'));
		} 
		$new_file = '';
		$path = '/Public/upload/kfhead/';
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $str, $result)){ 
		  $type = $result[2]; 
		  $new_file = $path.date('YmdHis').'_'.mt_rand(1000,9999).".{$type}"; 
		  if (!file_put_contents('.'.$new_file, base64_decode(str_replace($result[1], '', $str)))){
			$this->ajaxReturn(array('s'=>false,'m'=>'图片保存失败')); 
		  }
		}else{
			$this->ajaxReturn(array('s'=>false,'m'=>'图片数据错误'));
		}
		$img = 'D:/wwwroot'.$new_file;
		$rs = $this->wx->setKFHeadImg($kf_account,$img);
		if($rs['errcode']!=0){
			$this->ajaxReturn(array('s'=>false,'m'=>'设置头像失败'));
		}
		M('Kf')->where(array('kf_account'=>$kf_account))->save(array('kf_headimgurl'=>$new_file));
		$this->ajaxReturn(array('s'=>true,'m'=>'图片上传成功'));
	}
	
	public function kf_list(){
		
	 
		 
		//
		//$rs = $this->wx->deleteKFAccount('kf0002@zjit');  
		//$rs = $this->wx->deleteKFAccount('kf0004@zjit');  
		// 
		//$rs = $this->wx->updateKFAccount('kf001@weixinzjit','小强','123456');
		//$rs = $this->wx->addKFAccount('kf001@kefu','小强','123456');
		//$rs = $this->wx->inviteworkerAccount('kf001@kefu','nickyhb');
		$rs = $this->wx->getCustomServiceKFlist(); 
		//$rst = $this->wx->getKFSessionlist('kf0001@zjit');
		P($rst);
	}
	



	//服务记录
	public function service_list(){
		 
		//接收筛选信息
		$keyword=I('keyword');
		$type=I('type');
		$starttime=I('starttime'); //strtotime(I('starttime'));
		$endtime=I('endtime'); //strtotime(I('endtime'));
		if($starttime>$endtime){
			error('结束时间必须大于开始时间',$_SERVER['HTTP_REFERER']);
		}
		$wancheng=I('wancheng');
		
		$whereStr = ' `status` = 1 ';
		$whereArr = array();
		if(!empty($keyword)){
			$whereStr .= ' and kf_account like "%'. $keyword .'%" ';
			$whereArr['keyword'] = $keyword;
		}
		if(!empty($type)){
			$whereStr .= ' and `key` = "'.$type.'"';
			$whereArr['type'] = $type;
		}
		if(!empty($starttime)){
			$whereStr .= ' and created >= "'. strtotime($starttime) .'" ';
			$whereArr['starttime'] = $starttime;
		}
		if(!empty($endtime)){
			$whereStr .= ' and created <= "'. strtotime($endtime) .'" ';
			$whereArr['endtime'] = $endtime;
		}
		if(!empty($wancheng)){
			$whereStr .= ' and sta = '. $wancheng ;
			$whereArr['wancheng'] = $wancheng;
		}
		
		//服务类型
		$list_key=M('sckey')->select();
		$user = session('LG_USER');
		$name=$user['username'];
		if ($name!='admin') {
			$list_m=M('rbac_manager')->where('username="'.$name.'"')->find();
			$openid=$list_m['openid'];
			$list_k=M('kf')->where('openid="'.$openid.'"')->find();
			$kf_account=$list_k['kf_account'];
			
			$whereStr .= ' and `kf_account` = "'.$kf_account.'"';
			
			$service=M('kf_sc_log');
			$count      = $service->where($whereStr)->count();// 查询满足要求的总记录数
			$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $service->limit($Page->firstRow.','.$Page->listRows)->where($whereStr)->order('created desc')->select();//打印出所有的人
			foreach ($list as $key => $value) {
				$da=M('customer')->where('openid="'.$value['openid'].'"')->find();
				$list[$key]['user']=$da['name'];
				$list[$key]['phone']=$da['phone'];
				$kf_list=M('kf')->where('kf_account="'.$value['kf_account'].'"')->find();
				$list[$key]['kf_name']=$kf_list['kf_nickname'];
			}
				$arr=array('page'=>$show,'list'=>$list,'count'=>$count,'keyw'=>$keyword);
				//P($arr);exit;
				$this->assign('list',$arr);
				$this->display('service');
		
		}else{
			//$keyword=trim(I('keyword'));
		    //$where['openid|kf_account'] = array('like','%'.$keyword.'%');
			$service=M('kf_sc_log');
			$count      = $service->where($whereStr)->count();// 查询满足要求的总记录数
			//echo M()->getlastsql();exit('@@@');
			$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $service->limit($Page->firstRow.','.$Page->listRows)->where($whereStr)->order('created desc')->select();//打印出所有的人
			
			foreach ($list as $key => $value) {
				$da=M('customer')->where('openid="'.$value['openid'].'"')->find();
				$list[$key]['user']=$da['name'];
				$list[$key]['phone']=$da['phone'];
				$kf_list=M('kf')->where('kf_account="'.$value['kf_account'].'"')->find();
				$list[$key]['kf_name']=$kf_list['kf_nickname'];
			}
			//P($whereArr);
			//P($list);
			$arr=array('page'=>$show,'list'=>$list,'count'=>$count,'keyw'=>$keyword);
			$this->assign('list_key',$list_key);
			$this->assign('whereArr',$whereArr); 
			$this->assign('list',$arr); 
			$this->display('service');
		}
	}



		//客服添加个人备注页面
		public function add_bei_index(){
			$id=I('id');			
			$this->assign('id',$id);
			$this->display('add_bei');
		}
		// 客服添加个人备注
		public function add_bei(){
			$id=I('id');
			$beizhu=trim(I('beizhu'));
			$data=array(
					'beizhu'=>$beizhu,
					'time'=>time(),
				);
			$res=M('kf_sc_log')->where('id="'.$id.'"')->data($data)->save();
			//echo M()->_sql();exit;
			if (false!==$res) {
				$this->redirect('Customer/service_list');
			}else{
				error('添加失败',$_SERVER['HTTP_REFERER']);
			}

		}
		//客服查看个人备注
		public function bei_index(){
			$id=I('id');
			$list=M('kf_sc_log')->where('id="'.$id.'"')->find();	
			$this->assign('id',$id);		
			$this->assign('list',$list);
			$this->display('beizhu');
		}
		
		//客服完成状态
		public function wancheng(){
			$id=I('id');
			$sta=I('wancheng');
			$data=array(
				'sta'=>$sta,
			);
			$res=M('kf_sc_log')->where('id="'.$id.'"')->save($data);
			if(!false==$res){
				$this->ajaxReturn(array('s'=>"ok",'m'=>"修改成功"));
			}
			
			
		}
		
	//导出csv格式的表格
	
	public function exportcsv() {
		//接收筛选信息
		$keyword=I('keyword');
		$type=I('type');
		$starttime=I('starttime'); //strtotime(I('starttime'));
		$endtime=I('endtime'); //strtotime(I('endtime'));
		if($starttime>$endtime){
			error('结束时间必须大于开始时间',$_SERVER['HTTP_REFERER']);
		}
		$wancheng=I('wancheng');
		
		$whereStr = ' `status` = 1 ';
		$whereArr = array();
		if(!empty($keyword)){
			$whereStr .= ' and kf_account like "%'. $keyword .'%" ';
			$whereArr['keyword'] = $keyword;
		}
		if(!empty($type)){
			$whereStr .= ' and `key` = "'.$type.'"';
			$whereArr['type'] = $type;
		}
		if(!empty($starttime)){
			$whereStr .= ' and created >= "'. strtotime($starttime) .'" ';
			$whereArr['starttime'] = $starttime;
		}
		if(!empty($endtime)){
			$whereStr .= ' and created <= "'. strtotime($endtime) .'" ';
			$whereArr['endtime'] = $endtime;
		}
		if(!empty($wancheng)){
			$whereStr .= ' and sta = '. $wancheng ;
			$whereArr['wancheng'] = $wancheng;
		}
		$service=M('kf_sc_log');
		
		//P($list);
		$str = "服务对象,服务对象联系方式,服务类型,服务时间,客服评价,客服编号,完成状况,客服备注\r\n";
		
		$user = session('LG_USER');
		$name=$user['username'];
		if ($name!='admin') {
			$list_m=M('rbac_manager')->where('username="'.$name.'"')->find();
			$openid=$list_m['openid'];
			$list_k=M('kf')->where('openid="'.$openid.'"')->find();
			$kf_account=$list_k['kf_account'];
			$whereStr .= ' and `kf_account` = "'.$kf_account.'"';
			$list = $service->where($whereStr)->order('created desc')->select();
		}else{
			$list = $service->where($whereStr)->order('created desc')->select();
		}
		
		
		
		foreach($list as $key=>$value){
			
			$openid = $value['openid'];
			$customer=M('customer')->where('openid="'.$openid.'"')->find();
			$list[$key]['c_name']=$customer['name'];
			$list[$key]['phone']=$customer['phone'];
			
		}
		//P($list);
		foreach($list as $k => $value){
			$name=$value['c_name'];
			$phone=$value['phone'];
			$key=$value['key'];
			$created=date('Y-m-d H:i:s',$value['created']);
			$ping_ja=$value['ping_ja'];
			$kf_account=$value['kf_account'];
			$sta=$value['sta'];
			if($sta==1){
				$sta='未完成';
			}else{
				
				$sta='完成';
			}
			$beizhu=$value['beizhu'];
			
			$str .= "".$name.",".$phone.",".$key.",".$created.",".$ping_ja.",".$kf_account.",".$sta.",".$beizhu."\r\n";
		} 
		$filename = date('Ymd').'.csv'; //设置文件名
		if(filesize($file)>1024){
			$file = getcwd().'/aaa.csv';
			//dump($file);exit;
			file_put_contents($file,$str);
			//dump($str);exit;
			if (file_exists($file)) {
					$filesize=filesize($file)+1000;
					
					header('Content-Description:File Transfer');
					header('Content-type:'.csv);
					header('Content-Transfer-Encoding:binary');
					header("Accept-Ranges: bytes");
					header('Expires:0');
					header('Cache-Control:must-revalidate');
					header('Pragma:public');
					header("Content-Length:".$filesize);
					header('Content-Disposition: attachment; filename='.$filename);
						//打开文件
						$fp = fopen($file, "rb");
						//dump($fp);exit;
						//设置指针位置
						fseek($fp,0);
						while (!feof($fp)) {
							//虚幻输出
							//设置文件最长执行时间
							set_time_limit(0);
							print (fread($fp, 1024 * 150)); //输出文件
							flush(); //输出缓冲
							ob_flush();
						}
						fclose($fp);
					
					unlink($file);
					exit ();
				}else{
					echo "err";die();
				}
			}else{
				header("Content-type:text/csv");
				header("Content-Disposition:attachment;filename=".$filename);
				header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
				header('Expires:0');
				header('Pragma:public');
				$str = iconv('utf-8', 'gb2312', $str);
				echo $str;
			}
		} 	
	
		
		//新增管理员
		public function add_old_manger(){
			$name=I('name');
			$phone=I('phone');
			$list=M('old_manager')->where('phone="'.$phone.'"')->find();
			if(!empty($list)){
				$this->ajaxReturn(array('s'=>"no",'m'=>"添加失败，手机号已经存在"));
			}
			$data=array('name'=>$name,'phone'=>$phone);
			$res=M('old_manager')->add($data);
			if($res!==false){
				$this->ajaxReturn(array('s'=>"ok",'m'=>"添加成功"));
			}
			
		}
		
		
		
		
		//聊天记录
		
	public function talk_log(){
		
		$id=I('id');
		$list = M('kf_sc_log')->where('id="'.$id.'"')->find();
		//服务的用户
		$openid = $list['openid'];
		//服务的客服编号
		$kefu = $list['kf_account'];
		
		//开始时间
		$stime = $list['created'];
		
		//结束时间，就是下一次的开始时间
		$endtime_list = M('kf_sc_log')->where('created>"'.$stime.'"')->order('created asc')->find();
		//echo M()->_sql();
		if(!empty($endtime_list)){
			$etime=$endtime_list['created'];
		}else{
			$etime=time();
		}
		

		$rs = $this->_getMesLog($openid,$kefu,$stime,$etime); 

		//获取接收到的数据
		$result = $rs;

		//P($result,false);
		
		$where = ' openid="'.$openid.'" and worker="'.$kefu.'" and time>='.$stime.' and time<= '.$etime;
		$sMes = M('Msglog')->where($where)->select();
		
		$sendMes = array();
		foreach($sMes as $ms){
			$tar = $ms;
			$tar['time'] = intval($ms['time']);
			$tar['opercode'] = intval($ms['opercode']);
			$sendMes[] = $tar;
		}
		
		$result = array_merge($result,$sendMes);
 		
		if(empty($result)){
			//$this->_ajax(false,'Empty');
		}
		
		$result = $this->array_sort($result,'time','asc');
		
		$returndata = array();
		foreach($result as $re){
			$returndata[] = $re;
		}
		//P($returndata);
		$this->assign('list',$returndata);
		$this->display('talk_log');
		//$this->_ajax(true,'Success',array('endtime'=>$etime,'result'=>$returndata));
		
	}
	
	//从服务器获取聊天记录
	function _getMesLog($openid,$kefu,$sTime,$etime){ 
		//P($openid,false);P($kefu,false);P($sTime,false);P($etime,false);
		$dat = array(
			'starttime'	=>	$sTime,
			'endtime'	=>	$etime,
			'pageindex'	=>	1,
			'pagesize'	=>	50,
		); 
		//P($dat,false);
		//$this->_ajax(false,'Empty',$dat);
		//$rst = $this->wx->getKFSessionlist('kf0001@zjit');
		$rs = $this->wx->getCustomServiceMessage($dat); 
		//P($rs,false);
		//处理返回数据 
		$returnData = array();
		foreach($rs['recordlist'] as $lin){
			if($openid == $lin['openid'] && $kefu == $lin['worker'] ) $returnData[] = $lin;
		}
		//P($returnData,false);
		return $returnData;
	}
		
		
	function array_sort($arr,$keys,$type='asc'){ 
		 $keysvalue = $new_array = array();
		 foreach ($arr as $k=>$v){
		  	$keysvalue[$k] = $v[$keys];
		 }
		 if($type == 'asc'){
		  	asort($keysvalue);
		 }else{
		  	arsort($keysvalue);
		 }
		 reset($keysvalue);
		 foreach ($keysvalue as $k=>$v){
		  	$new_array[$k] = $arr[$k];
		 }
		 return $new_array; 
	}
	
	
	/**
	* Ajax数据返回
	* @return
	*/
	function _ajax($s,$m,$d){
		$this->ajaxReturn(array('s'=>$s,'m'=>$m,'d'=>$d));
	}
	
	
	
	//导出本次的聊天记录
	public function export_talk_log(){
		$id=I('id');
		$list = M('kf_sc_log')->where('id="'.$id.'"')->find();
		//服务的用户
		$openid = $list['openid'];
		//服务的客服编号
		$kefu = $list['kf_account'];
		
		//开始时间
		$stime = $list['created'];
		
		//结束时间，就是下一次的开始时间
		$endtime_list = M('kf_sc_log')->where('created>"'.$stime.'"')->order('created asc')->find();
		//echo M()->_sql();
		if(!empty($endtime_list)){
			$etime=$endtime_list['created'];
		}else{
			$etime=$stime+"3600";
		}
		

		$rs = $this->_getMesLog($openid,$kefu,$stime,$etime); 

		//获取接收到的数据
		$result = $rs;

		//P($result,false);
		
		$where = ' openid="'.$openid.'" and worker="'.$kefu.'" and time>='.$stime.' and time<= '.time();
		$sMes = M('Msglog')->where($where)->select();
		
		$sendMes = array();
		foreach($sMes as $ms){
			$tar = $ms;
			$tar['time'] = intval($ms['time']);
			$tar['opercode'] = intval($ms['opercode']);
			$sendMes[] = $tar;
		}
		
		$result = array_merge($result,$sendMes);
 		
		$result = $this->array_sort($result,'time','asc');
		
		$returndata = array();
		foreach($result as $re){
			$returndata[] = $re;
		}
		//P($returndata,false);
		
		$str = "客户发送时间,客户发送内容,客服发送内容,客服发送时间\r\n";
		foreach($returndata as $key=>$value){
			//P($value);
			$opercode=$value['opercode'];
			if($opercode=="2003"){
				$text=$value['text'];
				$str .="".date('Y-m-d H:i:s',$value['time']).",".$text.",,\r\n";
			}
			if($opercode=="2002"){
				$text=$value['text'];
				//$str .=,,"".date('Y-m-d H:i:s').",".$text."\r\n";
				$str .=",,".$text.",".date('Y-m-d H:i:s',$value['time'])."\r\n";
			}
			
//			$ctime = date('Y-m-d H:i:s',$value['ctime']);
//			$str .= "".$id.",".$name.",".$subscribe.",".$openid.",".$nickname.",".$sex.",".$city.",".$country.",".$province.",".$language.",".$headimgurl.",".$subscribe_time.",".$unionid.",".$remark.",".$ctime.",".$groupid."\r\n";
		}
		$filename = date('Ymd').'.csv'; //设置文件名
		if(filesize($file)>1024){
			$file = getcwd().'/aaa.csv';
			//dump($file);exit;
			file_put_contents($file,$str);
			//dump($str);exit;
			if (file_exists($file)) {
					$filesize=filesize($file)+1000;
					
					header('Content-Description:File Transfer');
					header('Content-type:'.csv);
					header('Content-Transfer-Encoding:binary');
					header("Accept-Ranges: bytes");
					header('Expires:0');
					header('Cache-Control:must-revalidate');
					header('Pragma:public');
					header("Content-Length:".$filesize);
					header('Content-Disposition: attachment; filename='.$filename);
						//打开文件
						$fp = fopen($file, "rb");
						//dump($fp);exit;
						//设置指针位置
						fseek($fp,0);
						while (!feof($fp)) {
							//虚幻输出
							//设置文件最长执行时间
							set_time_limit(0);
							print (fread($fp, 1024 * 150)); //输出文件
							flush(); //输出缓冲
							ob_flush();
						}
						fclose($fp);
					
					unlink($file);
					exit ();
				}else{
					echo "err";die();
				}
			}else{
				header("Content-type:text/csv");
				header("Content-Disposition:attachment;filename=".$filename);
				header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
				header('Expires:0');
				header('Pragma:public');
				$str = iconv('utf-8', 'gb2312', $str);
				echo $str;
			}
	
	}
		
		
}